package com.lzk.org.service.impl;

import com.lzk.basic.service.impl.BaseServiceImpl;
import com.lzk.org.domain.Department;
import com.lzk.org.mapper.DepartmentMapper;
import com.lzk.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        update(department);
    }


    @Override
    @Transactional
    public void update(Department department) {

        if (department.getParent_id()==null){
            Long id = department.getId();
            //设置dirPath
            department.setDirPath("/"+id);
        }else{ //2.有上级部门
            //通过parent_id 获取上级的dirPath
            //获取上级部门id
            Long parent_id = department.getParent_id();
            //父级部门对象
            Department byid = departmentMapper.loadById(parent_id);
            //dirPath
            department.setDirPath(byid.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }
    @Override
    public List<Department> deptTree() {
        //1.查询所有数据，循环遍历放入map
        List<Department> all = departmentMapper.loadAll();
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department : all) {
            map.put(department.getId(), department);
        }
        //2.创建一个空的数组为部门树,将数据传给前端
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : all) {//顶级部门
            if (department.getParent_id() == null) {
                deptTree.add(department);
            }else {//子部门就放入child_department
                Long parent_id = department.getParent_id();

                Department parentDepartment = map.get(parent_id);

                parentDepartment.getChildren().add(department);
            }
        }

        return deptTree;
    }

}
